<template>
  <div class="examine-container">
    <!-- 游戏审核部分 -->
    <div class="game-examine">
      <h2 class="section-title">游戏审核</h2>
      <div class="game-card" v-if="currentGame">
        <!-- 游戏基本信息 -->
        <div class="game-content">
          <div class="game-image">
            <img :src="currentGame.photo" :alt="currentGame.gname">
          </div>
          <div class="game-info">
            <div class="info-row">
              <span class="label">游戏名称：</span>
              <span>{{ currentGame.gname }}</span>
            </div>
            <div class="info-row">
              <span class="label">开发商：</span>
              <span>{{ currentGame.company }}</span>
            </div>
            <div class="info-row">
              <span class="label">游戏类型：</span>
              <span>{{ currentGame.tname }}</span>
            </div>
            <div class="info-row">
              <span class="label">更多分类：</span>
              <span>{{ currentGame.moretype }}</span>
            </div>
            <div class="info-row">
              <span class="label">发售日期：</span>
              <span>{{ currentGame.onsaledate }}</span>
            </div>
            <div class="info-row">
              <span class="label">游戏价格：</span>
              <span>¥{{ currentGame.price }}</span>
            </div>
            <div class="info-row description">
              <span class="label">游戏描述：</span>
              <p>{{ currentGame.detail }}</p>
            </div>
          </div>
        </div>

        <!-- 游戏预览图 -->
        <div class="game-preview-images">
          <h3 class="preview-title">游戏预览图</h3>
          <div class="preview-grid">
            <div class="preview-item" v-if="currentGame.photoa">
              <img :src="currentGame.photoa" alt="预览图1">
            </div>
            <div class="preview-item" v-if="currentGame.photob">
              <img :src="currentGame.photob" alt="预览图2">
            </div>
            <div class="preview-item" v-if="currentGame.photoc">
              <img :src="currentGame.photoc" alt="预览图3">
            </div>
            <div class="preview-item" v-if="currentGame.photod">
              <img :src="currentGame.photod" alt="预览图4">
            </div>
          </div>
        </div>

        <!-- 游戏视频 -->
        <div class="game-video" v-if="currentGame.video">
          <h3 class="preview-title">游戏视频</h3>
          <video controls :src="currentGame.video" class="video-player"></video>
        </div>

        <!-- 审核操作区 -->
        <div class="action-area">
          <div class="review-input">
            <el-input
              v-model="reviewComment"
              type="textarea"
              placeholder="请输入审核评语"
              :rows="3"
            />
          </div>
          <div class="button-group">
            <el-button 
              type="success" 
              @click="handleGameApprove"
              :loading="isSubmitting"
            >
              通过
            </el-button>
            <el-button 
              type="danger" 
              @click="handleGameReject"
              :loading="isSubmitting"
            >
              不通过
            </el-button>
            <el-button 
              type="primary" 
              @click="handleGameDownload"
              :disabled="!currentGame?.path"
            >
              下载游戏文件
            </el-button>
          </div>
        </div>

        <!-- 游戏分页器 -->
        <div class="pagination" v-if="uncheckedGames.length > 0">
          <el-pagination
            background
            layout="prev, pager, next"
            :total="uncheckedGames.length"
            :page-size="1"
            v-model:current-page="gameCurrentPage"
            @current-change="handleGamePageChange"
          />
        </div>
      </div>

      <!-- 空状态 -->
      <div v-if="!currentGame && !isLoading" class="no-content">
        <el-empty description="暂无待审核游戏" />
      </div>

      <!-- 加载状态 -->
      <div v-if="isLoading" class="loading-container">
        <el-skeleton :rows="10" animated />
      </div>
    </div>

    <!-- 评论审核部分 -->
    <div class="comment-examine section">
      <h2 class="section-title">评论审核</h2>
      
      <div class="comment-table" v-if="comments.length > 0">
        <el-table
          :data="currentPageComments"
          style="width: 100%"
          :cell-style="{ background: '#1e2837', color: '#ffffff', borderBottom: '1px solid #3a4557' }"
        >
          <el-table-column prop="mname" label="用户名" width="120" />
          <el-table-column prop="gname" label="游戏" width="180" />
          <el-table-column prop="review" label="内容">
            <template #default="scope">
              <div class="comment-content">{{ scope.row.review }}</div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button
                type="success"
                size="small"
                @click="handleCommentApprove(scope.row)"
                :loading="isSubmitting"
              >
                通过
              </el-button>
              <el-button
                type="danger"
                size="small"
                @click="handleCommentReject(scope.row)"
                :loading="isSubmitting"
              >
                不通过
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination">
          <el-pagination
            background
            layout="prev, pager, next"
            :total="comments.length"
            :page-size="commentPageSize"
            v-model:current-page="commentCurrentPage"
          />
        </div>
      </div>

      <div v-else class="no-content">
        <el-empty description="暂无待审核评论" />
      </div>
    </div>
  </div>
</template>
<script>
import { ref, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { myAxios } from '../../axios/index'

export default {
  name: 'Examine',
  setup() {
    const uncheckedGames = ref([])
    const currentGame = ref(null)
    const gameCurrentPage = ref(1)
    const reviewComment = ref('')
    const isSubmitting = ref(false)
    const isLoading = ref(false)
    const comments = ref([])
    const commentCurrentPage = ref(1)
    const commentPageSize = 5

    // 计算当前页的评论
    const currentPageComments = computed(() => {
      const start = (commentCurrentPage.value - 1) * commentPageSize
      const end = start + commentPageSize
      return comments.value.slice(start, end)
    })

    // 处理游戏页面变化
    const handleGamePageChange = (page) => {
      gameCurrentPage.value = page
      currentGame.value = uncheckedGames.value[page - 1]
      reviewComment.value = '' // 切换游戏时清空评语
    }

    // 获取待审核游戏列表
    const fetchUncheckedGames = async () => {
      try {
        isLoading.value = true
        const response = await myAxios.get('/goodsAdmin/getUnchecked')
        console.log(response.data)
        
        if (response.data.code === 200) {
          uncheckedGames.value = response.data.data
          gameCurrentPage.value = 1
          currentGame.value = uncheckedGames.value.length > 0 ? uncheckedGames.value[0] : null
        } else {
          throw new Error(response.data.message || '获取待审核游戏失败')
        }
      } catch (error) {
        console.error('获取待审核游戏失败:', error)
        ElMessage.error('获取待审核游戏失败')
      } finally {
        isLoading.value = false
      }
    }

    // 获取待审核评论列表
    const fetchComments = async () => {
      try {
        const response = await myAxios.get('/userAdmin/findComment')
        console.log(response.data)
        if (response.data.code === 200) {
          comments.value = response.data.data
        } else {
          throw new Error(response.data.message || '获取待审核评论失败')
        }
      } catch (error) {
        console.error('获取待审核评论失败:', error)
        ElMessage.error('获取待审核评论失败')
      }
    }

    // 处理游戏审核
    const handleGameStatus = async (isApproved) => {
      if (!reviewComment.value) {
        ElMessage.warning('请输入审核评语')
        return
      }

      try {
        isSubmitting.value = true
        const url = isApproved ? '/goodsAdmin/pass' : '/goodsAdmin/unpassed'
        
        const response = await myAxios.put(url, `gid=${currentGame.value.gid}&reason=${reviewComment.value}`, {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    })
        console.log(response.data)
        console.log(currentGame.value.gid)
        console.log(reviewComment.value)
        if (response.data.code === 200) {
          ElMessage.success(isApproved ? '游戏审核通过' : '游戏审核未通过')
          reviewComment.value = ''
          await fetchUncheckedGames()
        } else if (response.data.code === 401) {
          ElMessage.error('没有权限进行此操作')
        } else if (response.data.code === 500) {
          ElMessage.error('服务器异常，请稍后重试')
        } else {
          throw new Error(response.data.message || '审核操作失败')
        }
      } catch (error) {
        console.error('审核失败:', error)
        ElMessage.error('审核操作失败')
      } finally {
        isSubmitting.value = false
      }
    }

    // 处理评论审核
    const handleCommentStatus = async (comment, isApproved) => {
      try {
        isSubmitting.value = true
        const url = isApproved ? '/userAdmin/pass' : '/userAdmin/unpassed'
        
        const response = await myAxios.post(url, `rid=${comment.rid}`, {
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          }
        })

        if (response.data.code === 200) {
          ElMessage.success(isApproved ? '评论审核通过' : '评论审核未通过')
          await fetchComments()
        } else if (response.data.code === 401) {
          ElMessage.error('没有权限进行此操作')
        } else {
          throw new Error(response.data.message || '评论审核操作失败')
        }
      } catch (error) {
        console.error('评论审核失败:', error)
        ElMessage.error('评论审核操作失败')
      } finally {
        isSubmitting.value = false
      }
    }

    const handleGameApprove = () => handleGameStatus(true)
    const handleGameReject = () => handleGameStatus(false)
    const handleCommentApprove = (comment) => handleCommentStatus(comment, true)
    const handleCommentReject = (comment) => handleCommentStatus(comment, false)

    const handleGameDownload = () => {
      if (currentGame.value?.path) {
        fetch(currentGame.value.path, {
          method: 'GET',
        })
        .then(response => response.blob())
        .then(blob => {
          const url = window.URL.createObjectURL(blob);
          const a = document.createElement('a');
          a.href = url;
          a.download = currentGame.value.gname || 'game';
          a.click();
          window.URL.revokeObjectURL(url);
          
          // 使用小弹窗显示成功提示
          ElMessage({
            message: '下载成功',
            type: 'success',
            duration: 2000,  // 显示2秒
            showClose: true, // 显示关闭按钮
            center: true     // 居中显示
          })
        })
        .catch(() => {
          // 使用小弹窗显示失败提示
          ElMessage({
            message: '下载失败',
            type: 'error',
            duration: 2000,
            showClose: true,
            center: true
          })
        })
      } else {
        // 使用小弹窗显示警告提示
        ElMessage({
          message: '没有可下载的游戏文件',
          type: 'warning',
          duration: 2000,
          showClose: true,
          center: true
        })
      }
    }

    onMounted(() => {
      fetchUncheckedGames()
      fetchComments()
    })

    return {
      currentGame,
      uncheckedGames,
      gameCurrentPage,
      reviewComment,
      isSubmitting,
      isLoading,
      comments,
      commentCurrentPage,
      commentPageSize,
      currentPageComments,
      handleGamePageChange,
      handleGameApprove,
      handleGameReject,
      handleGameDownload,
      handleCommentApprove,
      handleCommentReject
    }
  }
}
</script>
<style scoped>
.examine-container {
  height: calc(100vh - 72px);
  width: 100%;
  background-color: #1e2837;
  color: #ffffff;
  overflow-x: hidden;
}

.game-examine, .comment-examine {
  max-width: 960px;
  margin: 0 auto;
  padding: 10px;
  box-sizing: border-box;
}

.section-title {
  color: #409eff;
  font-size: 24px;
  margin-bottom: 20px;
  font-weight: 600;
  padding: 10px;
}

.game-card {
  background: #2a3444;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  width: 100%;
  box-sizing: border-box;
}

.game-content {
  display: flex;
  gap: 30px;
  margin-bottom: 30px;
  flex-wrap: wrap;
}

.game-image {
  width: 300px;
  height: 400px;
  overflow: hidden;
  border-radius: 8px;
  flex-shrink: 0;
}

.game-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.game-info {
  flex: 1;
  min-width: 300px;
}

.info-row {
  margin-bottom: 15px;
  font-size: 16px;
}

.label {
  color: #909399;
  margin-right: 10px;
}

.description p {
  margin-top: 10px;
  line-height: 1.6;
  color: #a8b3c5;
  word-break: break-word;
}

.preview-title {
  color: #409eff;
  font-size: 18px;
  margin-bottom: 15px;
}

.preview-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
  width: 100%;
}

.preview-item {
  aspect-ratio: 16/9;
  overflow: hidden;
  border-radius: 8px;
  width: 100%;
}

.preview-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.game-video {
  margin-bottom: 30px;
  width: 100%;
}

.video-player {
  width: 100%;
  max-height: 500px;
  border-radius: 8px;
}

.action-area {
  border-top: 1px solid #3a4557;
  padding-top: 20px;
  margin-bottom: 20px;
  width: 100%;
}

.review-input {
  margin-bottom: 20px;
  width: 100%;
}

.button-group {
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
}

.no-content {
  text-align: center;
  padding: 60px 0;
  background: #2a3444;
  border-radius: 8px;
  margin-top: 20px;
  width: 100%;
}

.comment-examine {
  background: #2a3444;
  border-radius: 8px;
  padding: 20px;
  margin-top: 20px;
  width: 100%;
  box-sizing: border-box;
}

.comment-content {
  white-space: pre-wrap;
  word-break: break-word;
  max-height: 100px;
  overflow-y: auto;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  width: 100%;
}

:deep(.el-input__inner),
:deep(.el-textarea__inner) {
  background-color: #2a3444;
  border-color: #3a4557;
  color: #ffffff;
  width: 100%;
}

/* 表格基础样式 */
:deep(.el-table) {
  --el-table-border-color: #3a4557;
  --el-table-header-bg-color: #2a3444;
  --el-table-header-text-color: #ffffff;
  --el-table-text-color: #fffff;
  --el-table-row-hover-bg-color: #3a4557;
  background-color: transparent !important;
  width: 100% !important;
  table-layout: fixed;
  border: none !important;
}

/* 完全移除表格边框 */
:deep(.el-table), 
:deep(.el-table__inner-wrapper),
:deep(.el-table__header-wrapper),
:deep(.el-table__body-wrapper) {
  background-color: transparent !important;
  border: none !important;
}

:deep(.el-table::before),
:deep(.el-table::after),
:deep(.el-table__inner-wrapper::after) {
  display: none !important;
}

/* 表头样式 */
:deep(.el-table__header) {
  border: none !important;
  margin: 0 !important;
}

:deep(.el-table__header-wrapper) {
  background-color: transparent !important;
  border: none !important;
}

:deep(.el-table th.el-table__cell) {
  background-color: #2a3444 !important;
  border-bottom: 1px solid #3a4557 !important;
  border-right: none !important;
  padding: 12px 0;
}

/* 表格内容样式 */
:deep(.el-table__body) {
  background-color: transparent !important;
}

:deep(.el-table__body tr) {
  background-color: #1e2837 !important;
}

:deep(.el-table td.el-table__cell) {
  background-color: #1e2837 !important;
  border-bottom: 1px solid #3a4557 !important;
}

:deep(.el-table .cell) {
  text-align: center !important;
  white-space: pre-wrap;
  word-break: break-word;
}

/* 内容列(第三列)的单元格左对齐 */
:deep(.el-table td.el-table__cell:nth-child(3)) {
  text-align: left !important;
}

:deep(.el-table td.el-table__cell:nth-child(3) .cell) {
  text-align: left !important;
  padding: 0 15px;
}

:deep(.el-table--enable-row-hover .el-table__body tr:hover > td.el-table__cell) {
  background-color: #3a4557;
}

/* 分页器样式 */
:deep(.el-pagination) {
  --el-pagination-bg-color: #2a3444;
  --el-pagination-text-color: #ffffff;
  --el-pagination-button-color: #ffffff;
  --el-pagination-hover-color: #409eff;
}

:deep(.el-pagination.is-background .el-pager li:not(.is-disabled).is-active) {
  background-color: #409eff;
}

:deep(.el-pagination.is-background .el-pager li) {
  background-color: #2a3444;
}

:deep(.el-pagination.is-background .btn-prev),
:deep(.el-pagination.is-background .btn-next) {
  background-color: #2a3444;
}

:deep(.el-pagination.is-background .btn-prev:disabled),
:deep(.el-pagination.is-background .btn-next:disabled) {
  background-color: #1e2837;
  color: #606266;
}

:deep(.el-pagination.is-background .btn-prev:hover:not([disabled])),
:deep(.el-pagination.is-background .btn-next:hover:not([disabled])) {
  background-color: #3a4557;
}

/* 滚动条样式 */
::-webkit-scrollbar {
  width: 8px;
}

::-webkit-scrollbar-track {
  background: #0f172a;
}

::-webkit-scrollbar-thumb {
  background: #334155;
  border-radius: 4px;
}

::-webkit-scrollbar-thumb:hover {
  background: #475569;
}
</style>